import { ConversationGroupList, getChatTitle, modelList } from "@/api/chat";
import { clerStorage } from "./storage/storage"
import router from "@/router"
import { useChatStoreWithOut } from "@/store/modules/chat";
import { userInfo } from "@/types/app";
import { ConversationGroupListFace, ModelTypeCace } from "@/types/chat.type";
import JSEncrypt from "jsencrypt";
import { ElMessage } from "element-plus";
const chatStore = useChatStoreWithOut();
const emp = ['null', 'undefined']
export const logout = () => {
  clerStorage()
  router?.push('/login')
}

export const isEmpData = (k: string) => {
  return emp.includes(k)
}
// 使用RSA密码加密方式
export const encrypt = (text: string) => {
  const encrypt = new JSEncrypt();
  encrypt.setPublicKey(
    `MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAt4VKlnBJ8ZqtL/975xzG
      0WrUlHjcJJwWifVscuJH6Gv652uVqb8B0c5cvB/sMGPhb6BObdFsiPwfwO3ahDem
      3pglH4Ugp/+auy8Hia8bXum4qXlVWvyXuXTZBXtqV8d5/scw4qXRXn5/PGX5nKHK
      3sDhs3rkE0FWE30C5jZ3EW+b58RRau5gogHyjSXEQybLkohCP0YkMj5wM4QZgSgU
      s1ch219wfl2X3BdMkU9whH4W28by3xJrUAcPcpHOBTF7TRGCmTmzLD9wz8QFnlU7
      7GYvduCA3Hp5bxzdsbmKeCWu5MFQQQ6cTRNRzGjKv5+FzLmv3efQRcO0yXIKRd6K
      kwIDAQAB`,
  );
  const encrypted = encrypt.encrypt(text);
  return encrypted;
};


export function smoothScrollToBottom(id: string, duration = 1000) {
  const element = document.getElementById(id);
  if (!element) return;
  let s = element.scrollTop
  function animation() {
    s += duration
    element.scrollTo(0, s);
    if (element.scrollHeight - s > duration) {
      requestAnimationFrame(animation)
    }
  }
  requestAnimationFrame(animation)
}

export const initChat = async (res: userInfo) => {
  try {
    const modelListRes = await modelList<{
      list: Array<ModelTypeCace>;
      total: number;
    }>()

    chatStore.setCurrentModelId(res.modelId)
    chatStore.setCurrentModel(res.modelName)
    chatStore.setModelList(modelListRes.list)
    const data = modelListRes.list.find(e => e.id == res.modelId)
    if (data) {
      const models = data.models.split(',')
      chatStore.setModels(models)
    }
  } catch (error) {
    console.log(error)
  }

}
export const initConversationGroup = async () => {
  const GroupRes = await ConversationGroupList<{
    list: ConversationGroupListFace[];
    total: number;
  }>();
  chatStore.setConversationGroup(GroupRes.list)
}
export const getTitel = async (s: string): Promise<string> => {
  const content = `将以下这段话输出一个标题，10个字以内，不需要其他内容 \n ${s}`
  const res: { message: string } = await getChatTitle({ content })
  return res.message
}



export function useCopyCode() {
  const timeoutIdMap: WeakMap<HTMLElement, NodeJS.Timeout> = new WeakMap()
  window.addEventListener('click', (e) => {
    let el = e.target as HTMLElement
    if (el.matches('.markdown-copy-text')) {
      el = el.parentElement
    }
    if (!el.matches('.markdown-code-copy')) {
      return
    }
    const parent = el.parentElement
    const sibling = parent?.nextElementSibling
    if (!parent || !sibling) {
      return
    }
    const isShell = /language-(shellscript|shell|bash|sh|zsh)/.test(
      parent.className
    )

    const ignoredNodes = []

    // Clone the node and remove the ignored nodes
    const clone = sibling.cloneNode(true) as HTMLElement
    if (ignoredNodes.length) {
      clone
        .querySelectorAll(ignoredNodes.join(','))
        .forEach((node) => node.remove())
    }

    let text = clone.textContent || ''

    if (isShell) {
      text = text.replace(/^ *(\$|>) /gm, '').trim()
    }
    ElMessage.success("复制成功")
    copyToClipboard(text).then(() => {
      el.classList.add('copied')
      clearTimeout(timeoutIdMap.get(el))
      const timeoutId = setTimeout(() => {
        el.classList.remove('copied')
        el.blur()
        timeoutIdMap.delete(el)
      }, 2000)
      timeoutIdMap.set(el, timeoutId)
    })
  })
}

async function copyToClipboard(text: string) {
  try {
    return navigator.clipboard.writeText(text)
  } catch {
    const element = document.createElement('textarea')
    const previouslyFocusedElement = document.activeElement

    element.value = text

    // Prevent keyboard from showing on mobile
    element.setAttribute('readonly', '')

    element.style.contain = 'strict'
    element.style.position = 'absolute'
    element.style.left = '-9999px'
    element.style.fontSize = '12pt' // Prevent zooming on iOS

    const selection = document.getSelection()
    const originalRange = selection
      ? selection.rangeCount > 0 && selection.getRangeAt(0)
      : null
    debugger
    document.body.appendChild(element)
    element.select()

    // Explicit selection workaround for iOS
    element.selectionStart = 0
    element.selectionEnd = text.length

    document.execCommand('copy')
    document.body.removeChild(element)

    if (originalRange) {
      selection!.removeAllRanges() // originalRange can't be truthy when selection is falsy
      selection!.addRange(originalRange)
    }

    // Get the focus back on the previously focused element, if any
    if (previouslyFocusedElement) {
      (previouslyFocusedElement as HTMLElement).focus()
    }
  }
}